#include "myhttpd.h"
#include "list_client.h"
#include "initialize.h"
#include "create_socket.h"
#include "list_msg.h"
#include "utility.h"
#include "get_message.h"

/*
** Principal function which allow to get a list of last clients'
** messages from select()
** RETURN : A list of messages
*/
s_msg *get_msg(s_client **list, fd_set *select_list, int svr_socket)
{
  s_msg *list_msg = NULL;
  int	nb_socketready;

  select_list_init(*list, select_list, svr_socket);
  nb_socketready = select(FD_SETSIZE, select_list, NULL, NULL, NULL);

  if (nb_socketready < 0 )
    exit(EXIT_FAILURE);
  else if (nb_socketready > 0)
    list_msg = fill_list_msg(svr_socket, select_list, list);

  return (list_msg);
}

/*
** Fill the list of clients'messages
** RETURN : A list of messages
*/
s_msg *fill_list_msg(int svr_socket, fd_set *select_list, s_client **list_client)
{
  s_client	*tmp;
  s_msg		*list_msg	= NULL;
  s_msg		*msg;
  char		*data;

  if (FD_ISSET(svr_socket, select_list))
      new_connection(list_client, svr_socket, select_list);

  tmp = *list_client;
  data = malloc(sizeof (char) * 4096);
  while (tmp != NULL)
  {
    if (FD_ISSET(tmp->socket,select_list))
    {
      msg = NULL;
      if(myrecv(tmp->socket, data, 4096, 0) == 0)
      {
	delete_client(list_client, tmp);
	FD_CLR(tmp->socket, select_list);
      }
      else
      {
	msg = init_msg(tmp->socket, data);
	add_msg(&list_msg, msg);
      }
    }
    tmp = tmp->next;
  }

  return (list_msg);
}

/*
** Handle a new connection (new client) :
** New socket and add client to the list of client
*/
void new_connection(s_client **list_client, int svr_socket, fd_set *select_list)
{
  s_client	*client = NULL;
  int		socket;

  socket = myaccept(svr_socket, NULL, NULL);
  set_non_blocking(socket);
  client = init_client(socket);
  add_client(list_client, client);
  FD_SET(client->socket, select_list);
}
